package org.xxpay.mch.user.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.JsonUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.MchPayPassage;
import org.xxpay.core.entity.MchQrCode;
import org.xxpay.core.entity.PayPassage;
import org.xxpay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: dingzhiwei
 * @date: 17/12/21
 * @description:
 */
@Controller
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/mch_qrcode")
@PreAuthorize("hasRole('"+ MchConstant.MCH_ROLE_NORMAL+"')")
public class MchQrCodeController extends BaseController {

    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增商户二维码" )
    public ResponseEntity<?> add(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        handleParamAmount(param, "minAmount", "maxAmount");
        String appId = getStringRequired(param, "appId");
        String channels = getStringRequired(param, "channels");
        channels = HtmlUtils.htmlUnescape(channels); //获取转义前的真实的数据
        Boolean result = checkChannel(getUser().getId(), channels);
        if (!result) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PAY_PASSAGE_ERROR));
        }
        String codeName = getStringRequired(param, "codeName");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setAppId(appId);
        mchQrCode.setChannels(channels);
        mchQrCode.setCodeName(codeName);
        if(param.getString("minAmount") != null) mchQrCode.setMinAmount(param.getLong("minAmount"));
        if(param.getString("maxAmount") != null) mchQrCode.setMaxAmount(param.getLong("maxAmount"));
        int count = commonService.mchQrCodeService.add(mchQrCode);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        String appId = getStringRequired(param, "appId");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setAppId(appId);
        int count = commonService.mchQrCodeService.count(mchQrCode);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<MchQrCode> mchQrCodeList = commonService.mchQrCodeService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), mchQrCode);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(mchQrCodeList, count));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/view_code")
    @ResponseBody
    public ResponseEntity<?> viewCode(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setId(id);
        mchQrCode = commonService.mchQrCodeService.find(mchQrCode);
        if(mchQrCode == null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_QR_CODE_STOP));
        }
        if(MchConstant.PUB_YES != mchQrCode.getStatus().byteValue()) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_RECORD_NOT_EXIST));
        }
        DBApplicationConfig dbConfig = commonService.sysConfigService.getDBApplicationConfig();
        StringBuilder sb = new StringBuilder(dbConfig.getConfig4PayUrl() + "/qrcode/toQRCodePage?");
        sb.append("mchId=").append(mchQrCode.getMchId()).append("&appId=").append(mchQrCode.getAppId())
                .append("&qrcodeId=").append(mchQrCode.getId());


        JSONObject data = new JSONObject();
        data.put("codeUrl", sb.toString());
        // codeUrl = '/api/payment/qrcode_img_get?' + 'url=' + data.payParams.codeUrl + '&widht=200&height=200';
        data.put("codeImgUrl", dbConfig.getConfig4MchApiUrl() +  "/payment/qrcode_img_get?url=" + MyBase64.encode(sb.toString().getBytes()) + "&widht=200&height=200");
        return ResponseEntity.ok(XxPayResponse.buildSuccess(data));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setMchId(getUser().getId());
        mchQrCode.setId(id);
        mchQrCode = commonService.mchQrCodeService.find(mchQrCode);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(mchQrCode));
    }

    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "修改商户二维码" )
    public ResponseEntity<?> update(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        handleParamAmount(param, "minAmount", "maxAmount");
        Long id = getLongRequired(param, "id");
        String channels = param.getString("channels");
        channels = HtmlUtils.htmlUnescape(channels); //获取转义前的真实的数据
        String codeName = param.getString("codeName");
        Byte status = param.getByte("status");
        MchQrCode mchQrCode = new MchQrCode();
        mchQrCode.setId(id);
        Boolean result = checkChannel(getUser().getId(), channels);
        if (!result) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_MCH_PAY_PASSAGE_ERROR));
        }
        if(StringUtils.isNotBlank(channels)) mchQrCode.setChannels(channels);
        if(StringUtils.isNotBlank(codeName)) mchQrCode.setCodeName(codeName);
        if(status != null) mchQrCode.setStatus(status);
        if(param.getString("minAmount") != null) mchQrCode.setMinAmount(param.getLong("minAmount"));
        if(param.getString("maxAmount") != null) mchQrCode.setMaxAmount(param.getLong("maxAmount"));
        int count = commonService.mchQrCodeService.update(mchQrCode);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    private Boolean checkChannel(Long mchId, String channels){
        JSONArray jsonArray = JSON.parseArray(channels);
        // 查询当前商户配置的通道
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject json = JsonUtil.getJSONObjectFromJson(jsonArray.get(i).toString());
            String channelId = json.getString("channelId");
            String productId = json.getString("productId");
            MchPayPassage mchPayPassage = commonService.mchPayPassageService.findByMchIdAndProductId(mchId, Integer.valueOf(productId));
            // 判断是否存在当前创建的通道
            if (mchPayPassage == null) return false;
            // 判断此通道状态
            if (mchPayPassage.getStatus() != Constant.PUB_YES) return false;
            // 根据接口模式查询通道
            Byte ifMode = mchPayPassage.getIfMode();
            // 单独模式
            if (ifMode == MchConstant.MCH_PAY_PASSAGE_IFMODE_ONE) {
                PayPassage payPassage = commonService.payPassageService.findById(mchPayPassage.getPayPassageId());
                if (payPassage.getStatus() != MchConstant.PUB_YES) return false;
                if (!"alipay_qr_h5".equals(channelId)) {
                    if (!channelId.equals(payPassage.getIfCode())) return false;
                }
            }
            // 轮询模式
            else if (ifMode == MchConstant.MCH_PAY_PASSAGE_IFMODE_TWO) {
                String pollParam = mchPayPassage.getPollParam();
                JSONArray pollParamArray = JSON.parseArray(pollParam);
                Boolean result = false;
                ArrayList<Integer> list = new ArrayList<>();
                for (int j = 0; j < pollParamArray.size(); j++) {
                    JSONObject pollParamJson = JsonUtil.getJSONObjectFromJson(pollParamArray.get(j).toString());
                    String payPassageId = pollParamJson.getString("payPassageId");
                    list.add(Integer.valueOf(payPassageId));
                }
                // in id List
                List<PayPassage> payPassageList = commonService.payPassageService.selectInPassageId(list);
                for (PayPassage passage : payPassageList) {
                    // 支付通道是否存在 状态是否可用
                    if (channelId.equals(passage.getIfCode()) && passage.getStatus() == MchConstant.PUB_YES){
                        result = true;
                    }
                }
                if (!result) return false;
            }
        }
        return true;
    }

}
